package com.zhang.gulimall.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhang.gulimall.common.utils.R;
import com.zhang.gulimall.common.vo.GiteeUser;
import com.zhang.gulimall.member.entity.MemberLevelEntity;
import com.zhang.gulimall.member.service.MemberLevelService;
import com.zhang.gulimall.member.vo.UserLoginVo;
import com.zhang.gulimall.member.vo.UserRegisterVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhang.gulimall.common.utils.PageUtils;
import com.zhang.gulimall.common.utils.Query;

import com.zhang.gulimall.member.dao.MemberDao;
import com.zhang.gulimall.member.entity.MemberEntity;
import com.zhang.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public R register(UserRegisterVo user) {
        if (!hasEmail(user.getEmail())) {
            return R.error("邮箱重复");
        }
        if (!hasUserName(user.getUserName())) {
            return R.error("用户名重复");
        }
        MemberEntity member = new MemberEntity();
        BeanUtils.copyProperties(user, member);
        // 密码加密
        member.setPassword(new BCryptPasswordEncoder().encode(member.getPassword()));
        // 设置会员等级
        MemberLevelEntity memberLevel = memberLevelService.getOne(
                new QueryWrapper<MemberLevelEntity>().lambda().eq(MemberLevelEntity::getDefaultStatus, 1));
        member.setLevelId(memberLevel.getId());
        member.setIntegration(0);

        baseMapper.insert(member);

        return R.ok();
    }

    @Override
    public R login(UserLoginVo user) {
        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MemberEntity::getUsername, user.getUserName())
                .or().eq(MemberEntity::getEmail, user.getUserName());
        MemberEntity entity = this.getOne(queryWrapper);
        if (entity == null) {
            return R.error("用户名不存在");
        }
        return new BCryptPasswordEncoder().matches(user.getPassword(), entity.getPassword()) ?
                R.ok().put("data", entity) : R.error("用户名或密码不正确");
    }

    @Override
    public R login(GiteeUser user) {
        //1.判断当前用户是否注册过
        MemberEntity member = this.getOne(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getSocialId, user.getId()));

        if (member == null) { // 注册
            member = new MemberEntity();
            member.setSocialId(String.valueOf(user.getId()));
            member.setAccessToken(user.getAccess_token());
            member.setRefreshToken(user.getRefresh_token());
            member.setIntegration(0);
            // 设置会员等级
            MemberLevelEntity memberLevel = memberLevelService.getOne(
                    new QueryWrapper<MemberLevelEntity>().lambda().eq(MemberLevelEntity::getDefaultStatus, 1));
            member.setLevelId(memberLevel.getId());
            // 昵称
            member.setNickname(user.getName());
            return baseMapper.insert(member) > 0 ? R.ok("注册成功") : R.error("注册失败");
        } else { // 登录
            member.setSocialId(String.valueOf(user.getId()));
            member.setAccessToken(user.getAccess_token());
            member.setRefreshToken(user.getRefresh_token());
            return baseMapper.updateById(member) > 0 ? R.ok("登录成功") : R.error("用户信息更新失败");
        }
    }

    public Boolean hasEmail(String email) {
        List<MemberEntity> list = baseMapper.selectList(
                new QueryWrapper<MemberEntity>()
                        .lambda().eq(MemberEntity::getEmail, email));
        return list.size() <= 0;
    }

    public Boolean hasUserName(String userName) {
        List<MemberEntity> list = baseMapper.selectList(
                new QueryWrapper<MemberEntity>()
                        .lambda().eq(MemberEntity::getUsername, userName));
        return list.size() <= 0;
    }

}